package service

import (
	"admin100/app/dao"
	"admin100/app/model"
	"admin100/app/model/commonmodel"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"math"
	"time"
)

var SettingDataService SettingData

type SettingData struct {
}

func (s *SettingData) Add(u *model.MyadminUser, r *model.SettingDataServiceAddReq) int64 {
	data := g.Map{
		dao.SettingData.Columns.Name:       r.Name,
		dao.SettingData.Columns.State:      r.State,
		dao.SettingData.Columns.ChangeTime: int(gtime.Timestamp()),
		dao.SettingData.Columns.UserId:     u.Id,
	}
	res, err := dao.SettingData.Insert(data)
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	InsertId, err := res.LastInsertId()
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	return InsertId
}

func (s *SettingData) Edit(u *model.MyadminUser, r *model.SettingDataServiceEditReq) bool {
	data := g.Map{
		dao.SettingData.Columns.Name:       r.Name,
		dao.SettingData.Columns.State:      r.State,
		dao.SettingData.Columns.ChangeTime: int(gtime.Timestamp()),
		dao.SettingData.Columns.UserId:     u.Id,
	}
	_, err := dao.SettingData.Where(dao.SettingData.Columns.Id, r.Id).Update(data)
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}
	return true
}

func (s *SettingData) List(r *model.SettingDataServiceListReq) (pageInfo commonmodel.PageInfo, list []interface{}) {

	nums, err := dao.SettingData.Count()
	defErr.IfPanic(err, define.DataOptFail)

	pageInfo = commonmodel.PageInfo{
		Total: nums,
		Cur:   r.Page,
		PNum:  int(math.Ceil(float64(nums) / float64(r.PageSize))),
	}

	data, err := dao.SettingData.Page(r.Page, r.PageSize).All()
	defErr.IfPanic(err, define.DataOptFail)

	adminMap := dao.MyadminUser.MapRes()

	var columns = dao.SettingData.Columns
	for _, v := range data {
		list = append(list, map[string]interface{}{
			columns.Id:         v.Id,
			columns.Name:       v.Name,
			columns.State:      v.State,
			"user_name":        adminMap[v.UserId],
			columns.ChangeTime: time.Unix(int64(v.ChangeTime), 0).Format("2006-01-02 15:04:05"),
		})
	}
	return pageInfo, list

}

func (s *SettingData) Del(r *model.SettingDatServicesDelReq) bool {

	_, err := dao.SettingData.Where("id IN (?)", r.Ids).Delete()
	if err != nil {
		defErr.Panic(define.DataOptFail)
	}

	return true
}
